package com.run.runbbs.service.impl;

import com.run.runbbs.dao.CommentMapper;
import com.run.runbbs.entity.Comment;
import com.run.runbbs.util.Constant;
import com.run.runbbs.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import java.util.List;


//@Scope注解：见->https://www.cnblogs.com/ysq0908/p/10692337.html
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
@Service
public class CommentService implements Constant {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private PostService postService;
    @Autowired
    private SensitiveFilter sensitiveFilter;

    public List<Comment> findCommentsByEntity(int entityType,int entityId,int offset,int limit){
        return commentMapper.selectCommentsByEntity(entityType,entityId,offset,limit);
    }
    public int findCommentCount(int entityType,int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment==null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        //过滤标签
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        //过滤敏感词
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int commentId=commentMapper.insertComment(comment);
        //更新帖子中评论的数量
        if(comment.getEntityType()==ENTITY_TYPE_POST){
            int count=commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
            postService.updateCommentCount(comment.getEntityId(),count);
        }
        return commentId;
    }
    public Comment findCommentById(int id){
        return commentMapper.selectCommentById(id);
    }
}
